const event = require("./listeners");
const jwt = require('jsonwebtoken');
const cookie = require('cookie');
const { User } = require("../models");
const { SECRETKEY, BASE_URL, DEFAULT_IAMGE } = require("../config");

module.exports = (server) => {
    const io = require("socket.io")(server, { transports: ["websocket"] });
    io.use((socket, next) => {
        const cookies = socket.handshake.headers.cookie;
        
        if (cookies == undefined) {
          return next();
        }

        const token = cookie.parse(cookies)['token'];
        console.log('客户端 token:', token);

        jwt.verify(token, SECRETKEY, async (err, decoded) => {
            if (err) {
                return next();
            }

            socket.userId = decoded.id;

            let doc_user = await User.findById(decoded.id);
            if (doc_user == null) { 
                return next(); 
            }
            doc_user.socketId = socket.id;
            await doc_user.save();

            let data = doc_user;
            (data.headImgUrl != DEFAULT_IAMGE) && (data.headImgUrl = BASE_URL + data.headImgUrl);
            (data.cover != DEFAULT_IAMGE) && (data.cover = BASE_URL + data.cover);
            
            console.log(doc_user.phone + '通过cookie登录成功');
            doc_user.joinedGroups.forEach(item => socket.join(item.toString()));
            
            socket.emit("cookie_verify_success", { status_code: 200, info: "登录成功", data });

            next();
        });
      });
    io.on("connection", socket => {
        event.forEach(({ name, fn }) => {
            socket.on(name, (data, callback) => fn(io, socket, data, callback))
        })
        socket.on("disconnect", async reason => {
            let user = await User.findOne({ socketId: socket.id })
            if (user == null) return;

            user.socketId = ""
            await user.save();

            console.log(`客户端断开连接: ${socket.id}`);
            console.log(`断开原因: ${reason}`);
            console.log(`客户端 IP: ${socket.handshake.address}`);
        });
    })
}